package com.zc.mall.exception;

import com.zc.mall.vo.ResponseVo;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

import static com.zc.mall.enums.ResponseEnum.*;

/**
 * @author 曾川
 * @version 1.0.0
 * @ClassName RuntimeExceptionHandler.java
 * @Description 异常捕获
 * @createTime 2021年06月04日 12:42:00
 */
@ControllerAdvice
public class RuntimeExceptionHandler {


    /**
     * 捕获RuntimeException异常 返回定义的json数据
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
//    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResponseVo handle(RuntimeException e){
        return ResponseVo.error(ERROR,e.getMessage());
    }


    @ExceptionHandler(UserLoginExcepiton.class)
    @ResponseBody
    public ResponseVo userLoginHandle(){
        return ResponseVo.error(NEED_LOGIN);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseVo notValidExceptionHandle(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Objects.requireNonNull(bindingResult.getFieldError());
        return ResponseVo.error(PARAM_ERROR,
                bindingResult.getFieldError().getField() + " "
                + bindingResult.getFieldError().getDefaultMessage());
    }

}
